package com.murphy.algorithm.likou;

import java.text.DecimalFormat;

/**
 * 二分查找
 * @author dongsufeng
 * @version 4.0
 * @date 2023/2/24 16:52
 */
public class ErSearch {

    public int search(int[] nums,int target){
        int l = 0;
        int r = nums.length - 1;
        while (r >= l){
            int mid = (r + l) / 2;
            if (nums[mid] > target){
                r = mid - 1;
            }else if (nums[mid] < target){
                l = mid + 1;
            }else {
                return mid;
            }
        }
        return -1;
    }

    public double sqrt(int num ,String format){
        double l = 0;
        double r = num;
        DecimalFormat df = new DecimalFormat(format);
        while (l <= r){
            double m = (r+l)/2;
            double  y = Double.valueOf(df.format(num/m));
            m = Double.valueOf(df.format(m));
            if (m == y){
                return m;
            }else if (m < y){
                l = m;
            }else {
                r = m;
            }
        }
        return -1;
    }


    public static void main(String[] args) {

        int[] nums = {2,4,6,8,9,23,35,67,78};
        ErSearch search = new ErSearch();
        System.out.println(search.search(nums,23));
        System.out.println(search.sqrt(4,"######0.0000000"));
    }
}
